package model

import (
	"github.com/share309/gorm_common/global"
	"gorm.io/gorm"
	"time"
)

type Video struct {
	VideoId     uint           `gorm:"column:video_id;type:int;comment:视频ID;primaryKey;not null;" json:"video_id"`                               // 视频ID
	Title       string         `gorm:"column:title;type:varchar(255);comment:视频标题;not null;" json:"title"`                                       // 视频标题
	Description string         `gorm:"column:description;type:text;comment:视频描述;" json:"description"`                                            // 视频描述
	Url         string         `gorm:"column:url;type:varchar(255);comment:视频URL;not null;" json:"url"`                                          // 视频URL
	Category    string         `gorm:"column:category;type:varchar(50);comment:视频分类;default:NULL;" json:"category"`                              // 视频分类
	UserId      uint           `gorm:"column:user_id;type:int;comment:上传用户ID;not null;" json:"user_id"`                                          // 上传用户ID
	CreatedAt   time.Time      `gorm:"column:created_at;type:datetime(3);comment:创建时间;not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"` // 创建时间
	UpdatedAt   time.Time      `gorm:"column:updated_at;type:datetime(3);comment:更新时间;not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"` // 更新时间
	DeletedAt   gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);comment:删除时间;default:NULL;" json:"deleted_at"`                          // 删除时间
}

func (v *Video) TableName() string {
	return "video"

}

type PageDto struct {
	Page     uint   `json:"page" form:"page"`
	PageSize uint   `json:"page_size" form:"page_size"`
	OrderBy  string `json:"order_by" form:"order_by"` // e.g. "created_at desc"
}

type PageResult[T any] struct {
	List     []T  `json:"list"`
	Total    uint `json:"total"`
	Page     uint `json:"page"`
	PageSize uint `json:"page_size"`
}

func Paginate[T any](where *T, req PageDto, out *[]T) (PageResult[T], error) {
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	offset := (req.Page - 1) * req.PageSize

	query := global.DB.Model(out).Where(where)

	// 统计总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return PageResult[T]{}, err
	}

	// 排序
	if req.OrderBy != "" {
		query = query.Order(req.OrderBy)
	}

	// 查询数据
	if err := query.Offset(int(offset)).Limit(int(req.PageSize)).Find(out).Error; err != nil {
		return PageResult[T]{}, err
	}

	return PageResult[T]{
		List:     *out,
		Total:    uint(total),
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}
